package com.cyq.controller;

import com.alibaba.fastjson.JSONArray;
import com.cyq.pojo.Role;
import com.cyq.pojo.User;
import com.cyq.service.RoleService;
import com.cyq.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    /*权限管理页面*/
    @RequiresRoles(value = {"admin","master"},logical = Logical.OR)
    @GetMapping("/role/list")
    public ModelAndView providerList() {
        ModelAndView mav = new ModelAndView();
        List<Role> roleList = roleService.getRoleList();
        mav.addObject("pageInfo",roleList);
        mav.setViewName("role/RoleList");
        return mav;
    }

    /*删除权限*/
    @RequiresRoles(value = {"admin"})
    @GetMapping("/role/roleDelete")
    public void userDelete(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("code");
        Map<String, String> resultMap = new HashMap<String, String>();

        try {
            int flag = roleService.deleteRoleById(Integer.parseInt(id));
            if (flag > 0) {
                resultMap.put("code", "success");
            } else {
                resultMap.put("code", "error");
            }
            response.setContentType("application/json");
            PrintWriter outPrintWriter = response.getWriter();
            outPrintWriter.write(JSONArray.toJSONString(resultMap));
            outPrintWriter.flush();//刷新
            outPrintWriter.close();//关闭流
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*权限查看*/
    @RequiresRoles(value = {"admin"})
    @GetMapping("/role/roleView/{id}")
    public ModelAndView providerView(@PathVariable("id") int proId) {
        ModelAndView mav = new ModelAndView();
        //根据id查询出当前选中的权限
        Role role = new Role();
        role.setId(proId);
        System.out.println(role);
        Role roleById = roleService.getRoleByRole(role);

        //获取创建人姓名
        User user = new User();
        user.setId(roleById.getCreatedBy());
        String creatName = userService.queryUserByUser(user).getUserName();
        //将数据传入前端
        mav.addObject("role", roleById);
        mav.addObject("creatName",creatName);
        mav.setViewName("role/RoleView");
        return mav;
    }

    /*跳转到权限添加界面*/
    @RequiresRoles(value = {"admin"})
    @GetMapping("/role/roleAdd")
    public ModelAndView toRoleAdd() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("role/RoleAdd");
        return mav;
    }

    /*权限添加*/
    @RequiresRoles(value = {"admin"})
    @PostMapping("/role/roleAdd")
    public ModelAndView roleAdd(Role role, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String method = request.getParameter("method");
        //当method为add时，代表全部输入合法，成功添加
        if (method.equals("add")) {
            role.setCreationDate(new Date());
            //获取当前用户
            Subject subject = SecurityUtils.getSubject();
            //封装用户的登录数据，这里的token是全局变量，可以在任意位置取出
            User currentUser = (User) subject.getPrincipal();
            role.setCreatedBy(currentUser.getId());
            int flag = 0;
            flag = roleService.addRole(role);
            System.out.println(role);
            System.out.println(flag);
            if (flag > 0) {
                mav.setViewName("redirect:/role/list");
            } else {
                mav.setViewName("/role/RoleAdd");
            }
        }
        //ajax动态验证登录账号roleCode是否已经存在
        else if (method.equals("rcExist")) {
            //判断权限编码是否可用
            String roleCode = request.getParameter("roleCode");
            //用于存放对userCode判断对结果
            Map<String, String> resultMap = new HashMap<String, String>();
            //判断userCode是否为空
            if (roleCode == null || ("").equals(roleCode)) {
                //userCode == null || userCode.equals("")
                resultMap.put("roleCode", "null");
            } else {
                Role role1 = new Role();
                role1.setRoleCode(roleCode);
                Role roleByRole = roleService.getRoleByRole(role1);
                if (null != roleByRole) {
                    resultMap.put("roleCode", "exist");
                } else {
                    resultMap.put("roleCode", "notExist");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                response.setContentType("application/json");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = response.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //ajax动态验证权限名roleName是否已经存在
        else if (method.equals("rnExist")) {
            //判断权限编码是否可用
            String roleName = request.getParameter("roleName");
            //用于存放对userCode判断对结果
            Map<String, String> resultMap = new HashMap<String, String>();
            //判断userCode是否为空
            if (roleName == null || ("").equals(roleName)) {
                //userCode == null || userCode.equals("")
                resultMap.put("roleName", "null");
            } else {
                Role role1 = new Role();
                role1.setRoleCode(roleName);
                Role roleByRole = roleService.getRoleByRole(role1);
                if (null != roleByRole) {
                    resultMap.put("roleCode", "exist");
                } else {
                    resultMap.put("roleCode", "notExist");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                response.setContentType("application/json");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = response.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mav;
    }
}
